package com.shangfutai.android.keymonitoringf5

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.function.Consumer

@RequiresApi(Build.VERSION_CODES.N)
class KeyMonitoringF5Receiver : BroadcastReceiver() {
    val pressTime: Long = 4000
    val dbclickTime: Long = 1000

    // 按键计时器
    val pressTimer: MutableMap<String?, Long> = HashMap()

    // 单击计数器
    val clickCounter: MutableMap<String, Int> = HashMap()

    // 按键事件映射
    val eventMapping: MutableMap<String, Consumer<Context>> = HashMap()

    val thread: ExecutorService = Executors.newScheduledThreadPool(20)
    var longpressEventHandleDoing = false

    init {
        eventMapping["SOS.down"] = object : Consumer<Context> {
            override fun accept(context: Context) {
                Log.e("========>","SOS.down")
                val intent = Intent()
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.action = "com.runbo.video.key.down"
                context.sendBroadcast(intent)
            }
        }
        eventMapping["SOS.up"] = object : Consumer<Context> {
            override fun accept(context: Context) {
                Log.e("========>","SOS.up")
                val intent = Intent()
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.action = "com.runbo.video.key.up"
                context.sendBroadcast(intent)
            }
        }
    }

    @SuppressLint("LongLogTag")
    override fun onReceive(context: Context, intent: Intent) {
        Log.i("==================>", intent.action!!)
        val action = intent.action.toString()
        val args = action.split(".")
        if (args.size < 4) {
            return
        }
        val key = args[3]
        val event = args[4]
        if ("down" != event && "up" != event) {
            return
        }
        handleEvent(context, key, event)
        thread.execute { // 单击检测
            clickEventHandle(context, key, event)
        }
        thread.execute { // 长按检测
            longpressEventHandle(context, key, event)
        }
    }

    // 点击检测
    fun clickEventHandle(cxt: Context, key: String, event: String) {
        if ("up" != event) {
            return
        }
        if (clickCounter.containsKey(key)) {
            handleEvent(cxt, key, "dbclick")
            clickCounter.remove(key)
        } else {
            clickCounter[key] = 1
            try {
                Thread.sleep(dbclickTime)
            } catch (e: InterruptedException) {
               Log.i("MyReceiver.sleep", e.message!!)
            }
            if (clickCounter.containsKey(key)) {
                handleEvent(cxt, key, "click")
                clickCounter.remove(key)
            }
        }
    }

    // 长按事件处理器
    fun longpressEventHandle(cxt: Context, pressKey: String?, event: String) {

        if ("up" == event) {
            pressTimer.remove(pressKey)
            return
        }
        pressTimer[pressKey] = System.currentTimeMillis()
        if (longpressEventHandleDoing) {
            return
        }
        longpressEventHandleDoing = true
        var time: Long
        val executedEvent: ArrayList<String> = ArrayList<String>()
        do {
            if (pressTimer.isEmpty()) {
                break
            }
            time = System.currentTimeMillis()
            for (key in pressTimer.keys) {
                if (time - pressTimer[key]!! >= pressTime) {
                    handleEvent(cxt, key, "longpress")
                    executedEvent.add(key!!)
                }
            }
            for (i in executedEvent.indices) {
                pressTimer.remove(executedEvent[i])
            }
            try {
                Thread.sleep(10)
            } catch (e: InterruptedException) {
               Log.i("MyReceiver.sleep", e.message!!)
            }
        } while (true)

        longpressEventHandleDoing = false

    }

    fun handleEvent(cxt: Context, key: String?, event: String) {
       Log.i("event=================>", "$key.$event")
        if (eventMapping.containsKey("$key.$event")) {
            eventMapping["$key.$event"]!!.accept(cxt)

        }
    }
}